/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.dao.impl;

import cz.muni.fi.pa165.creatures.dao.CreatureTypeDAO;
import cz.muni.fi.pa165.creatures.dao.utils.DAOUtils;
import cz.muni.fi.pa165.creatures.model.CreatureType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * This class represents the implementation of all basic operations upon
 * {@link cz.muni.fi.pa165.creatures.model.CreatureType} instances.
 *
 * @author xvojtis2
 */
@Repository
@Transactional
public class CreatureTypeDAOImpl implements CreatureTypeDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void create(CreatureType creatureType) {
        DAOUtils.notNull(creatureType);
        em.persist(creatureType);
    }

    @Override
    public void remove(CreatureType creatureType) {
        DAOUtils.notNull(creatureType);
        CreatureType toRemove =
                em.find(CreatureType.class, creatureType.getId());
        em.remove(toRemove);
    }

    @Override
    public void update(CreatureType creatureType) {
        DAOUtils.notNull(creatureType);
        em.merge(creatureType);
    }

    @Override
    public CreatureType get(Long id) {
        DAOUtils.notNull(id);
        return em.find(CreatureType.class, id);
    }

    @Override
    public Long getCount() {
        Query q = em.createQuery("select count(ct) from CreatureType as ct");
        return ((Long) q.getSingleResult());
    }

    @Override
    public List<CreatureType> getAll() {
        Query q = em.createQuery("from CreatureType");
        return q.getResultList();
    }

    @Override
    public void removeAll() {
        Query q = em.createQuery("delete from CreatureType ct");
        q.executeUpdate();
    }

    @Override
    public CreatureType getByName(String name) {
        DAOUtils.notNull(name);
        Query q = em.createQuery("select ct from CreatureType as ct "
                + "where ct.name = :name");
        q.setParameter("name", name);
        List result = q.getResultList();
        if (result.size() > 0) {
            return (CreatureType) result.get(0);
        } else {
            return null;
        }
    }

}
